import {tokenManage} from 'utils/Cache';
import {upload} from 'api/common/common';
import { Toast } from 'vant';

//拍照上传图片
const generalServiceImpl = {
  getImage() {
    let This = this;
    return new Promise((resolve, reject) => {
      var cmr = plus.camera.getCamera(); //获取摄像头管理对象
      var res = cmr.supportedImageResolutions[0]; //字符串数组，摄像头支持的拍照分辨率
      var fmt = cmr.supportedImageFormats[0]; //字符串数组，摄像头支持的拍照文件格式
      console.log("拍照分辨率: " + res + ", 拍照文件格式: " + fmt);
      cmr.captureImage(
        function(path) {
          //进行拍照操作
          // 通过URL参数获取目录对象或文件对象
          plus.io.resolveLocalFileSystemURL(path, function(entry) {
            This.imgsrc = entry.toLocalURL(); //获取目录路径转换为本地路径URL地址
            This.uploadHead(This.imgsrc).then(res => {
              resolve(res)
            })
          });
        },
        function(error) {
          //捕获图像失败回调
          // alert("捕获图像失败: " + error.message);
        },
        { resolution: res, format: fmt }
      );
    })
  },
  appendByGallery() {
    let This = this;
    return new Promise((resolve, reject) => {
      plus.gallery.pick(function(path){
        This.uploadHead(path).then(res => {
          resolve(res)
        })
      },function(error) {
//  	alert( "Capture image failed: " + error.message );
      },{filter:"image",filename:'_documents/siyuan/'});
    })
  },
  uploadHead(file) {
    let This = this
    return new Promise((resolve, reject) => {
      let _this = This
      let Orientation;
      let image = new Image();
      image.onload = function () {
        let that = _this
        var imgData = This.getBase64Image(image, Orientation);
        var blob = This.dataURItoBlob(imgData); // 上一步中的函数
        var form = new FormData(document.forms[0]);
        form.append("photos", blob, 'image.png');
        upload(form).then( res=> {
          Toast.loading({
            message: '上传中...',
            duration: 0
          });
          if (res.status == 1) {
            Toast.clear()
            Toast({
              message: '上传成功',
              duration: 1000
            })
            This.Headportrait = res.result[0]
            resolve(This.Headportrait)
          } else {
            Toast.clear()
            Toast({
              message: res.msg,
              duration: 1000
            })
          }
        })
      }
      image.src = file
    })
  },
  getBase64Image(img , orientation) {
    var imgWidth = img.width,
      imgHeight = img.height;
    //alert('宽'+img.width)
    //alert('高'+img.height)
    if(imgWidth > imgHeight && imgWidth > 1024){
      imgWidth = 1024;
      imgHeight = Math.ceil(1024 * img.height / img.width);
    } else if(imgWidth < imgHeight && imgHeight > 1365){
      imgWidth = Math.ceil(1365 * img.width / img.height);
      imgHeight = 1365;
    }


    var canvas = document.createElement("canvas"),
      ctx = canvas.getContext('2d');
    canvas.width = imgWidth;
    canvas.height = imgHeight;
    //alert('方向信息'+orientation)
    // alert('宽'+imgWidth)
    // alert('高'+imgHeight)
    if (orientation) {
      switch(orientation){
        case 6:     // 旋转90度
          canvas.width = imgHeight;
          canvas.height = imgWidth;
          ctx.rotate((90 * Math.PI) / 180);
          // (0,-imgHeight) 从旋转原理图那里获得的起始点
          ctx.drawImage(img, 0, -imgHeight, imgWidth, imgHeight);
          break;
        case 3:     // 旋转180度
          canvas.width = imgHeight;
          canvas.height = imgWidth;
          ctx.rotate((180 * Math.PI) / 180);
          ctx.drawImage(img, -imgWidth, -imgHeight, imgWidth, imgHeight);
          break;
        case 8:     // 旋转-90度
          canvas.width = imgHeight;
          canvas.height = imgWidth;
          ctx.rotate((-90 * Math.PI) / 180);
          ctx.drawImage(img, -imgWidth, 0, imgWidth, imgHeight);
          break;
        case 1:     // 旋转-90度
          canvas.width = imgHeight;
          canvas.height = imgWidth;
          // ctx.rotate((180 * Math.PI) / 180);
          ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
          break;

      }
    } else if ((orientation == undefined) && (imgWidth < imgHeight)) {
      canvas.width = imgWidth;
      canvas.height = imgHeight;
      ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
    }else if ((orientation == undefined) && (imgWidth > imgHeight)) {
      canvas.width = imgHeight;
      canvas.height = imgWidth;
      ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
    }else if ((orientation == 0 ) && (imgWidth < imgHeight)) {
      canvas.width = imgWidth;
      canvas.height = imgHeight;
      ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
    }else if ((orientation == 0 ) && (imgWidth > imgHeight)) {
      canvas.width = imgHeight;
      canvas.height = imgWidth;
      ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
    }else {
      canvas.width = imgHeight;
      canvas.height = imgWidth;
      ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
    }

    // 返回新图片
    let ndata = canvas.toDataURL('image/jpeg', 0.8);
    return ndata
  },
  dataURItoBlob(base64Data) {
    var byteString;
    if (base64Data.split(',')[0].indexOf('base64') >= 0)
      byteString = atob(base64Data.split(',')[1]);
    else
      byteString = unescape(base64Data.split(',')[1]);
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type:mimeString});
  },
}


export default generalServiceImpl;
